package http

import (
	"context"
	"flag"
	"git.huoys.com/block_chain/mall/configs"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/gin-gonic/gin"
)

var (
	port    string
	runMode string
)

type Server struct {
	conf   configs.Config
	router *gin.Engine
}

func NewSrv(conf configs.Config, r *gin.Engine) *Server {
	return &Server{
		conf:   conf,
		router: r,
	}
}

func (s *Server) RunApp() {
	// 获取指定参数
	s.setupFlag()
	server := &http.Server{
		Addr:           s.conf.GinServer.ServerAddr,
		Handler:        s.router,
		ReadTimeout:    time.Duration(s.conf.GinServer.ReadTimeout) * time.Second,
		WriteTimeout:   time.Duration(s.conf.GinServer.WriteTimeout) * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	log.Println("port", server.Addr)
	go func() {
		if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("s.ListenAndServe err: %v", err)
		}
	}()

	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	log.Println("Shuting down server...")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := server.Shutdown(ctx); err != nil {
		log.Fatal("Server forced to shutdown:", err)
	}

	log.Println("Server exiting")
}

func (s *Server) setupFlag() {
	flag.StringVar(&port, "port", "", "启动端口")
	flag.StringVar(&runMode, "mode", "", "启动模式")
	flag.Parse()
	if port != "" {
		s.conf.GinServer.ServerAddr = ":" + port
	}
	if runMode != "" {
		s.conf.GinServer.RunMode = runMode
	}
}
